"use client";

import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select";
import { Play, Pause, Expand, Edit } from "lucide-react";
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog";
import { Textarea } from "@/components/ui/textarea";

export default function ReadPage() {
  const router = useRouter();
  const [text, setText] = useState("视频拍摄管理系统创想家...");
  const [isScrolling, setIsScrolling] = useState(false);
  const [transformEnabled, setTransformEnabled] = useState(false);
  const [fontSize, setFontSize] = useState("48px");
  const [speed, setSpeed] = useState(200);
  const [isFullscreen, setIsFullscreen] = useState(false);
  const [elapsedTime, setElapsedTime] = useState(0);
  const [isDialogOpen, setIsDialogOpen] = useState(false);
  const scrollAreaRef = useRef<HTMLDivElement>(null);
  const intervalRef = useRef<NodeJS.Timeout>();

  const fontSizeOptions = [
    { label: "小 (48px)", value: "48px" },
    { label: "中 (60px)", value: "60px" },
    { label: "大 (90px)", value: "90px" },
    { label: "超大 (120px)", value: "120px" },
  ];

  const speedOptions = [
    { label: "很慢", value: 150 },
    { label: "慢速", value: 200 },
    { label: "正常", value: 240 },
    { label: "快速", value: 280 },
    { label: "很快", value: 320 },
  ];

  const duration = () => {
    const chineseLength = text.split("").filter(c => c.charCodeAt(0) > 255).length;
    const englishLength = text.length - chineseLength;
    const totalLength = chineseLength + englishLength;
    return ((totalLength / speed) * 60).toFixed(2);
  };

  const startScroll = (direction: "up" | "down") => {
    setIsScrolling(true);
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
    }
    
    intervalRef.current = setInterval(() => {
      if (scrollAreaRef.current) {
        const { scrollTop, scrollHeight, clientHeight } = scrollAreaRef.current;
        const maxScroll = scrollHeight - clientHeight;
        
        if (direction === "down") {
          if (scrollTop >= maxScroll) {
            scrollAreaRef.current.scrollTop = 0;
          } else {
            scrollAreaRef.current.scrollTop += 1;
          }
        } else {
          if (scrollTop <= 0) {
            scrollAreaRef.current.scrollTop = maxScroll;
          } else {
            scrollAreaRef.current.scrollTop -= 1;
          }
        }
      }
    }, 1000 / speed);
  };

  const stopScroll = () => {
    setIsScrolling(false);
    if (intervalRef.current) {
      clearInterval(intervalRef.current);
    }
  };

  const toggleFullscreen = async () => {
    try {
      if (!isFullscreen) {
        await document.documentElement.requestFullscreen();
      } else {
        await document.exitFullscreen();
      }
      setIsFullscreen(!isFullscreen);
    } catch (err) {
      console.error('Fullscreen error:', err);
    }
  };

  useEffect(() => {
    if (scrollAreaRef.current) {
      const { scrollHeight, clientHeight } = scrollAreaRef.current;
      if (transformEnabled) {
        // 镜像模式时滚动到底部
        scrollAreaRef.current.scrollTop = scrollHeight - clientHeight;
      } else {
        // 无镜像模式时滚动到顶部
        scrollAreaRef.current.scrollTop = 0;
      }
    }
  }, [transformEnabled]);

  useEffect(() => {
    const timer = setInterval(() => {
      if (isScrolling) {
        setElapsedTime(prev => prev + 1);
      }
    }, 1000);

    return () => clearInterval(timer);
  }, [isScrolling]);

  useEffect(() => {
    return () => {
      if (intervalRef.current) {
        clearInterval(intervalRef.current);
      }
    };
  }, []);

  return (
    <div className="w-full h-screen bg-black overflow-hidden relative">
      {/* Controls */}
      <div className="absolute top-0 left-0 right-0 z-50 bg-gradient-to-r from-gray-900/95 to-gray-800/95 backdrop-blur-md border-b border-gray-700/50 shadow-lg">
        <div className="p-4 flex items-center gap-4 max-w-7xl mx-auto">
          <Button 
            onClick={() => isScrolling ? stopScroll() : startScroll(transformEnabled ? "up" : "down")}
            className="bg-rose-600 hover:bg-rose-700 text-white font-medium px-6 py-2 rounded-lg transition-all duration-200 shadow-md"
          >
            {isScrolling ? <Pause className="mr-2 h-4 w-4" /> : <Play className="mr-2 h-4 w-4" />}
            {isScrolling ? "暂停" : "开始"}
          </Button>
      
          <div className="flex items-center gap-3 bg-gray-800/50 px-4 py-2 rounded-lg">
            <Label htmlFor="mirror-mode" className="text-gray-300 font-medium">镜像</Label>
            <Switch
              id="mirror-mode"
              checked={transformEnabled}
              onCheckedChange={setTransformEnabled}
              className="data-[state=checked]:bg-rose-600"
            />
          </div>
      
          <div className="flex items-center gap-3 bg-gray-800/50 px-4 py-2 rounded-lg">
            <Label className="text-gray-300 font-medium">字体</Label>
            <Select value={fontSize} onValueChange={setFontSize}>
              <SelectTrigger className="w-[100px] bg-gray-700 border-gray-600 text-white">
                <SelectValue placeholder="字体大小" />
              </SelectTrigger>
              <SelectContent className="bg-gray-800 border-gray-700">
                {fontSizeOptions.map(option => (
                  <SelectItem key={option.value} value={option.value} className="text-white hover:bg-gray-700">
                    {option.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
      
          <div className="flex items-center gap-3 bg-gray-800/50 px-4 py-2 rounded-lg">
            <Label className="text-gray-300 font-medium">速度</Label>
            <Select value={speed.toString()} onValueChange={value => setSpeed(Number(value))}>
              <SelectTrigger className="w-[100px] bg-gray-700 border-gray-600 text-white">
                <SelectValue placeholder="速度" />
              </SelectTrigger>
              <SelectContent className="bg-gray-800 border-gray-700">
                {speedOptions.map(option => (
                  <SelectItem key={option.value} value={option.value.toString()} className="text-white hover:bg-gray-700">
                    {option.label}
                  </SelectItem>
                ))}
              </SelectContent>
            </Select>
          </div>
      
          <Dialog open={isDialogOpen} onOpenChange={setIsDialogOpen}>
            <DialogTrigger asChild>
              <Button 
                variant="outline" 
                className="bg-gray-800/50 border-gray-600 text-gray-300 hover:bg-gray-700/80 hover:text-white transition-colors duration-200 shadow-sm"
              >
                <Edit className="mr-2 h-4 w-4" />
                编辑文本
              </Button>
            </DialogTrigger>
            <DialogContent className="max-w-2xl bg-gray-900 border-gray-700">
              <DialogHeader>
                <DialogTitle className="text-white">编辑提词器文本</DialogTitle>
              </DialogHeader>
              <Textarea
                className="min-h-[400px] bg-gray-800 border-gray-600 text-white placeholder-gray-400 focus:border-rose-500 focus:ring-2 focus:ring-rose-500/20 transition-all duration-200"
                value={text}
                onChange={(e) => setText(e.target.value)}
                placeholder="请输入提词器文本..."
              />
              <div className="flex justify-end gap-3">
                <Button 
                  variant="outline" 
                  onClick={() => setIsDialogOpen(false)} 
                  className="bg-gray-800/50 border-gray-600 text-gray-300 hover:bg-gray-700/80 hover:text-white transition-colors duration-200"
                >
                  取消
                </Button>
                <Button 
                  onClick={() => setIsDialogOpen(false)} 
                  className="bg-rose-600 hover:bg-rose-700 text-white shadow-md hover:shadow-lg transition-all duration-200"
                >
                  保存
                </Button>
              </div>
            </DialogContent>
          </Dialog>
      
          <Button 
            onClick={toggleFullscreen} 
            variant="outline" 
            className="bg-gray-800/50 border-gray-600 text-gray-300 hover:bg-gray-700/80 hover:text-white transition-colors duration-200 shadow-sm"
          >
            <Expand className="mr-2 h-4 w-4" />
            {isFullscreen ? "退出" : "全屏"}
          </Button>
      
          <div className="text-gray-300 ml-auto bg-gray-800/50 px-4 py-2 rounded-lg font-mono">
            <span className="text-rose-400">{elapsedTime}s</span> / <span className="text-gray-400">{duration()}s</span>
          </div>
        </div>
      </div>

       {/* Highlight line */}
       <div className="fixed top-1/2 left-0 right-0 z-40 pointer-events-none">
         <div 
           className="h-[8rem] bg-gradient-to-r from-rose-500/20 via-rose-400/30 to-rose-500/20 border-y-2 border-rose-400/50 shadow-lg"
           style={{
             transform: 'translateY(-50%)',
             boxShadow: '0 0 30px rgba(59, 130, 246, 0.3), inset 0 0 30px rgba(59, 130, 246, 0.1)'
           }}
         />
         <div 
           className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 w-2 h-2 bg-rose-400 rounded-full animate-pulse"
           style={{
             boxShadow: '0 0 10px rgba(59, 130, 246, 0.8)'
           }}
         />
       </div>

      {/* Text Area */}
      <div
        ref={scrollAreaRef}
        className="w-full h-screen bg-gradient-to-b from-black via-gray-900 to-black text-white px-20 overflow-y-scroll scroll-smooth"
        style={{
          scrollbarWidth: 'none',
          msOverflowStyle: 'none',
        }}
      >
        <style jsx>{`
          div::-webkit-scrollbar {
            display: none;
          }
        `}</style>
        
        <div className={transformEnabled ? "h-1/2" : "h-1/3 mt-24"} />
        <div
          className="text-center p-8 h-max"
          style={{
            fontSize,
            transform: transformEnabled ? "rotateX(180deg)" : "none",
            fontFamily: "'AlibabaPuHuiTi', 'PingFang SC', 'Microsoft YaHei', sans-serif",
          }}
        >
          <div className="h-max py-20 leading-relaxed whitespace-pre-line text-shadow-lg" style={{
            lineHeight: '1.6',
            textShadow: '2px 2px 4px rgba(0,0,0,0.5)',
            letterSpacing: '0.05em'
          }}>
            {text}
          </div>
        </div>
        <div className={transformEnabled ? "h-3/5" : "h-2/3"} />
      </div>
    </div>
  );
}